package com.javaDemo.ti;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;

/**
 * @ClassName: Dikdadeshuzi
 * @Auther: csy
 * @Date: 2021/12/17 15:48
 * @Description:
 */
public class Dikdadeshuzi {
    static  int result1=0;
    public static void main(String[] args) {
        int a[]={3,2,1,5,6,4};
        // topKFrequent(a,3);
        System.out.println(findKthLargest(a,2));
    }
    public static int findKthLargest(int[] nums, int k) {
        findKMax(nums,0,nums.length-1,k);
        return result1;
    }

    static void findKMax(int[] arr, int left, int right, int k) {
        int temp = partition(arr, left, right);
        if (temp == k - 1) {
            result1=arr[temp];
        } else if (temp > k - 1) {
            findKMax(arr, left, temp - 1, k);
        } else {
            findKMax(arr, temp + 1, right, k);
        }
    }

    static int partition(int[] arr, int left, int right) {
        int temp = arr[left];
        while (left < right) {
            while (temp >= arr[right] && left < right)
                --right;
            arr[left] = arr[right];
            while (temp <= arr[left] && left < right)
                ++left;
            arr[right] = arr[left];
        }

        arr[right] = temp;
        return right;
    }
    public static int[] topKFrequent(int[] nums, int k) {
        int[] result = new int[k];
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }

        Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
        // 根据map的value值正序排，相当于一个小顶堆
        PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue());
        for (Map.Entry<Integer, Integer> entry : entries) {
            queue.offer(entry);
            if (queue.size() > k) {
                queue.poll();
            }
        }
        for (int i = k - 1; i >= 0; i--) {
            result[i] = queue.poll().getKey();
        }
        return result;
    }
}
